package com.unhz.taigu.service.impl;

import com.alibaba.fastjson.JSON;
import com.unhz.generator.dao.ExpandImageMapper;
import com.unhz.generator.dao.InsoleImageMapper;
import com.unhz.generator.dao.InsoleMapper;
import com.unhz.generator.dao.ReportMapper;
import com.unhz.generator.enums.EnumStatus;
import com.unhz.generator.enums.EnumValid;
import com.unhz.generator.pojo.*;
import com.unhz.generator.utils.EmptyUtil;
import com.unhz.generator.utils.IsNumeric;
import com.unhz.generator.utils.Page;
import com.unhz.generator.utils.QINiu.Upload;
import com.unhz.generator.vo.InsoleVo;
import com.unhz.taigu.service.ExpandImageService;
import com.unhz.taigu.service.InsoleImageService;
import com.unhz.taigu.service.InsoleService;
import com.unhz.taigu.service.ReportImageService;
import javafx.beans.property.IntegerProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 魏运奇
 * @Description: 中底样品
 * @Date: Created in 上午 11:13 2018/1/29 0029
 * @Modified By: V1.0.0
 */
@Service
public class InsoleServiceImpl implements InsoleService{

    static final int PAGENUM = 1;
    static final int ENABLE= 1;
    @Autowired
    private InsoleMapper insoleMapper;
    @Autowired
    private InsoleImageService insoleImageService;
    @Autowired
    private ExpandImageService expandImageService;
    @Autowired
    private ReportImageService reportImageService;



    /**
     * 分页查询
     * @param pageNo 页数
     * @param keywords 关键词
     * @return
     */
    @Override
    public Page<Insole> selectInsoleList(String pageNo, Integer pageSize, String keywords,Integer roleId) {
        int pageNum = PAGENUM;
        boolean numok = IsNumeric.isNumeric(pageNo);
        if(numok){
            if(Integer.parseInt(pageNo)<=0){
                pageNo="1";
            }
            if(pageNo !=null && !"".equals(pageNo)){
                pageNum = Integer.parseInt((pageNo));
            }
        }
        int totalRecords = insoleMapper.getTotalRecordsByKeywords(keywords);
        Page page = new Page(pageNum,totalRecords);
        page.setPageSize(pageSize);
        Map<String ,Object> map = new HashMap<String,Object>();
        map.put("startIndex",page.getStartIndex());
        map.put("pageSize",page.getPageSize());
        map.put("keywords",keywords);
        //获取总记录数
        List<Insole> records = insoleMapper.selectInsoleList(map);
        page.setRecords(records);
        String uri = "/insole/selectList?keywords="+keywords+"&roleId="+roleId;
        page.setUri(uri);
//        //设置访问路径(分页)
//        StringBuffer strUrl=new StringBuffer("/insole/selectList?keywords=");
//        if(!EmptyUtil.isEmpty(keywords)){
//             strUrl=strUrl.append(keywords);
//        }
//        page.setUri(strUrl.toString());
        return page;
    }


    @Override
    public Insole selectById(Integer id) {
        Insole insole=insoleMapper.selectById(id);

        return insole;
    }

    @Override
    public String[] selectImageById(Integer id) {
        String[] insoleImages=insoleMapper.selectImageById(id);

        return insoleImages;
    }

    @Override
    public boolean deleteById(Integer id) {

        int flag=insoleMapper.deleteById(id);

        if(flag>0){
            return true;
        }

        return false;
    }

    @Override
    public void insoleUpdate(Insole insole) {
        insoleMapper.updateByPrimaryKeySelective(insole);
    }

    @Override
    public List<Insole> selectAllInsoles() {
        return insoleMapper.selectAllInsoles();
    }

    @Override
    public String changsStatus(Integer insoleId, Integer isenable,String adminName) {
        //修改用户的禁用启用状态
        Insole insole  = new Insole();
        insole.setId(insoleId);
        insole.setStatus(EnumStatus.CHECKING.getIndex());
        insole.setUpdateBy(adminName);
        int count = insoleMapper.updateByPrimaryKeySelective(insole);
        if( count > 0){
            return "success";
        }
        return "failed";




    }

    @Override
    public Insole selectShoes(Integer insoleId) {
        return insoleMapper.selectShoes(insoleId);
    }

    @Override

    public int inserInsole(Insole insole) {
        return insoleMapper.insertSelective(insole);
    }



    public String changeCheckStatus(Integer insoleId, Integer examine,String adminName) {
        //修改用户的禁用启用状态
        Insole insole = insoleMapper.selectByPrimaryKey(insoleId);
        Integer valid = insole.getValid();
        if(examine == EnumValid.FIRST_ENABLED.getIndex()){
            switch (valid){
                case 0:
                    valid = EnumValid.ENABLED.getIndex();
                    break;
                case 1:
                    valid = EnumValid.DISABLE.getIndex();
                    break;
                case 2:
                    valid = EnumValid.ENABLED.getIndex();
                    break;
            }
        }
        insole.setValid(valid);
        insole.setStatus(examine);
        insole.setCheckBy(adminName);
        int count = insoleMapper.updateByPrimaryKeySelective(insole);
        if( count > 0){
            return "success";
        }
        return "failed";
    }

    @Override
    public Insole selectInsoleByModel(String model) {
        return insoleMapper.selectInsoleByModel(model);
    }

    @Override
    public String addInsole(Insole insole, MultipartFile[] insoleImgs, MultipartFile[] unfoldImgs, MultipartFile[] reports) {
       boolean flag=true;
        //保存中底信息
        if(!EmptyUtil.isEmpty(insole)) {
            String shoesType = insole.getShoesType();
            String midsole = insole.getMidsole();
            int heelHeight = Integer.valueOf(insole.getHeelHeight());
//            insole.setStatus(EnumStatus.CHECKING.getIndex());
//            insole.setValid(EnumValid.FIRST_ENABLED.getIndex());
            String model = null;
            if (heelHeight < 30 && heelHeight > 0) {
                model = shoesType + "M" + midsole + "L";
            }
            if (heelHeight >= 30 && heelHeight <= 50) {
                model = shoesType + "M" + midsole + "M";
            }
            if (heelHeight > 51 && heelHeight <= 80) {
                model = shoesType + "M" + midsole + "H";
            }
            if (heelHeight > 80) {
                model = shoesType + "M" + midsole + "S";
            }
            boolean exist = true;
            while (exist) {
                exist = false;
                String val = "";
                Random random = new Random();
                //参数length，表示生成几位随机数
                for (int i = 0; i < 3; i++) {
                    String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
                    //输出字母还是数字
                    if ("char".equalsIgnoreCase(charOrNum)) {
                        //输出是大写字母还是小写字母
                        int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                        val += (char) (random.nextInt(26) + temp);
                    } else if ("num".equalsIgnoreCase(charOrNum)) {
                        val += String.valueOf(random.nextInt(10));
                    }
                }
                List<Insole> list = selectAllInsoles();   //查询全部中底
                if (list.size() > 0) {
                    for (Insole insoles : list) {
                        String models = insoles.getModel();
                        String insoleModel = models.substring(4, 7);
                        if (val.equals(insoleModel)) {
                            exist = true;
                        }
                    }
                }
                model = model + val;
            }
            insole.setModel(model);
            inserInsole(insole);   //添加中底
            Integer id = insole.getId();
            if(id<0){
                flag=false;
            }
            String createBy = insole.getCreateBy(); //创建人
            //判断中底图片是否不为空
            if (!EmptyUtil.isEmpty(insoleImgs)) {
                //添加中底图片
                try {
                    InsoleImage pojo = null;
                    for (MultipartFile insoleImg : insoleImgs) {
                        byte[] insoleByte = insoleImg.getBytes();
                        String imageUrl = Upload.getUrl(insoleByte);  //获取中底图片地址
                        pojo = new InsoleImage();
                        pojo.setInsoleId(id);
                        pojo.setCreateTime(new Date());
                        pojo.setImageUrl(imageUrl);
                        pojo.setValid(ENABLE);
                        pojo.setCreateBy(createBy);
                       int sign= insoleImageService.insertSelective(pojo);
                         if(sign<0){
                             flag=false;
                         }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //判断中底展开图片是否不为空
            if (!EmptyUtil.isEmpty(unfoldImgs)) {
                //添加中底图片
                try {
                    ExpandImage pojo = null;
                    for (MultipartFile unfoldImg : unfoldImgs) {
                        byte[] insoleByte = unfoldImg.getBytes();
                        String imageUrl = Upload.getUrl(insoleByte);  //获取中底展开图片地址
                        pojo = new ExpandImage();
                        pojo.setInsoleId(id);
                        pojo.setCreateTime(new Date());
                        pojo.setImageUrl(imageUrl);
                        pojo.setValid(1);
                        pojo.setCreateBy(createBy);
                        int sign = expandImageService.insertSelective(pojo);
                        if(sign<0){
                            flag=false;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //七牛云服务器
            //全路径
            //固定路径  CDN+路径

            //判断质检报告图片是否不为空
            if (!EmptyUtil.isEmpty(reports)) {
                //添加中底图片
                try {
                    Report pojo = null;
                    for (MultipartFile report : reports) {
                        byte[] insoleByte = report.getBytes();
                        String imageUrl = Upload.getUrl(insoleByte);  //获取质检报告图片地址
                        pojo = new Report();
                        pojo.setInsoleId(id);
                        pojo.setCreateTime(new Date());
                        pojo.setReportUrl(imageUrl);
                        pojo.setValid(1);
                        pojo.setCreateBy(createBy);
                        int sign=reportImageService.insertSelective(pojo);
                        if(sign<0){
                            flag=false;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        if(flag){
            return "success";
        }
        return " failure";
    }

    @Override
    public void keyPass(Insole insole) {
        insoleMapper.keyPass(insole);
    }

    @Override
    public String updateInsole(Insole insole,String adminName, MultipartFile[] insoleImgs, MultipartFile[] unfoldImgs, MultipartFile[] reports) {
        boolean flag=true;
        insole.setUpdateBy(adminName);
        insole.setStatus(1);
        String newModel=create(insole);


        //重新生成中底型号
        insole.setModel(newModel);
        insoleMapper.updateByPrimaryKeySelective(insole);
        Integer insoleId = insole.getId();
        String createBy = insole.getCreateBy();
        //删除中底图片
        insoleImageService.deleteInsoleImage(insoleId);
        if(insoleId < 0){
            flag = false;
        }
        //判断中底图片是否不为空
        if (!EmptyUtil.isEmpty(insoleImgs)) {
            //添加中底图片
            try {
                InsoleImage pojo = null;
                for (MultipartFile insoleImg : insoleImgs) {
                    byte[] insoleByte = insoleImg.getBytes();
                    String imageUrl = Upload.getUrl(insoleByte);  //获取中底图片地址
                    pojo = new InsoleImage();
                    pojo.setInsoleId(insoleId);
                    pojo.setCreateTime(new Date());
                    pojo.setImageUrl(imageUrl);
                    pojo.setValid(ENABLE);
                    pojo.setCreateBy(createBy);
                    int sign= insoleImageService.insertSelective(pojo);
                    if(sign<0){
                        flag=false;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //删除展示图片
        expandImageService.deleteExpandImage(insoleId);
        if (!EmptyUtil.isEmpty(unfoldImgs)) {
            //添加中底展开图片
            try {
                ExpandImage pojo = null;
                for (MultipartFile unfoldImg : unfoldImgs) {
                    byte[] insoleByte = unfoldImg.getBytes();
                    String imageUrl = Upload.getUrl(insoleByte);  //获取中底展开图片地址
                    pojo = new ExpandImage();
                    pojo.setInsoleId(insoleId);
                    pojo.setCreateTime(new Date());
                    pojo.setImageUrl(imageUrl);
                    pojo.setValid(1);
                    pojo.setCreateBy(createBy);
                    int sign = expandImageService.insertSelective(pojo);
                    if(sign<0){
                        flag=false;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //删除质检报告
        reportImageService.deleteReportImage(insoleId);
        //判断质检报告图片是否不为空
        if (!EmptyUtil.isEmpty(reports)) {
            //添加质检报告图片
            try {
                Report pojo = null;
                for (MultipartFile report : reports) {
                    byte[] insoleByte = report.getBytes();
                    String imageUrl = Upload.getUrl(insoleByte);  //获取质检报告图片地址
                    pojo = new Report();
                    pojo.setInsoleId(insoleId);
                    pojo.setCreateTime(new Date());
                    pojo.setReportUrl(imageUrl);
                    pojo.setValid(1);
                    pojo.setCreateBy(createBy);
                    int sign=reportImageService.insertSelective(pojo);
                    if(sign<0){
                        flag=false;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(flag){
        return "success";
    }
        return " failure";
    }

    @Override
    public InsoleVo selectOneInsoleByInsoleId(Integer insoleId) {
        return insoleMapper.selectOneInsoleByInsoleId(insoleId);
    }

    public Insole selectByPrimaryKey(Integer insoleId){
        return insoleMapper.selectByPrimaryKey(insoleId);
    }

    //生成中底型号
    public String create(Insole insole){
        //获取要修改的中底信息
        Insole oldInsole=selectByPrimaryKey(insole.getId());
        StringBuffer model=new StringBuffer();
        String midsole=""; //工艺 工艺（传统T、注塑P、树脂一体R）
        Integer heelHeight=0;  //跟高（高H中M低L超高跟S）
        String number;
        //判段鞋类型  男M女W童K）
        if("M".equals(insole.getShoesType())){
            model.append("M");
        }if("W".equals(insole.getShoesType())){
            model.append("W");
        }if("K".equals(insole.getShoesType())){
            model.append("K");
        }
        //鞋类型（中底M、鞋面V、大底B、鞋跟H） 目前只有中底一种型号
        model.append("M");
        //判断工艺
        if("T".equals(insole.getMidsole())){
            model.append("T");
        }if("P".equals(insole.getMidsole())){
            model.append("P");
        }if("R".equals(insole.getMidsole())){
            model.append("R");
        }
        //判断跟高
        heelHeight=Integer.parseInt(insole.getHeelHeight())*10;
        if(heelHeight<30){
            model.append("M");
        }
        if(heelHeight>=30&&heelHeight<=50){
            model.append("L");
        }
        if(heelHeight>=51&&heelHeight<=80){
            model.append("H");
        }
        if(heelHeight>80){
            model.append("S");
        }
        //截取后3位 例001
        number=insole.getModel().substring(oldInsole.getModel().length()-3,insole.getModel().length());
        model.append(number);
        return model.toString();
    }







}
